package com.lijinjiang.service;

import com.lijinjiang.dao.UserDao;
import com.lijinjiang.entity.User;
import com.lijinjiang.util.Utils;
import com.lijinjiang.view.ChangePwdView;
import com.lijinjiang.view.UserAttributeView;
import com.lijinjiang.view.UserManageView;

import javax.swing.*;
import javax.swing.border.EtchedBorder;
import java.awt.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 所有用户都有的操作
 */
public class UserService {
    private UserDao userDao = new UserDao();

    // 通过账号获取用户
    public User getUserByAccount(String account) {
        User user = userDao.selectUserByAccount(account);
        return user;
    }

    // 更新用户信息
    public void updateUserInfo(UserManageView manageView, UserAttributeView attributeView) {
        String account = attributeView.getAccountCombo().getText();
        String name = attributeView.getNameCombo().getText();
        String college = attributeView.getCollegeCombo().getText();
        int index = attributeView.getSexModel().getSelectedIndex();
        Byte sex = (byte) index;
        String phone = attributeView.getPhoneCombo().getValueField().getText();
        boolean isAdmin = attributeView.getIsAdminBox().isSelected();
        // 姓名、学院是否为空
        Utils.checkFieldNull(attributeView.getNameCombo().getValueField(), "姓名不能为空！");
        Utils.checkFieldNull(attributeView.getCollegeCombo().getValueField(), "学院不能为空！");
        // 根据账号获取用户
        User user = getUserByAccount(account);
        // 更新修改的内容
        user.setName(name);
        user.setCollege(college);
        user.setSex(sex);
        user.setPhone(phone);
        user.setAdmin(isAdmin);
        boolean updated = userDao.updateUser(user);// 添加用户
        if (!updated) {
            // 如果更新失败
            JOptionPane.showMessageDialog(null, "更新" + account + "用户信息失败", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        manageView.refreshTableData(); // 刷新数据
        attributeView.dispose();
        JOptionPane.showMessageDialog(null, "更新" + account + "用户信息成功！");

    }

    // 获取所有用户信息
    public List<User> getAllUser() {
        List<User> list = userDao.selectUserBySql("select * from user order by account", null);
        return list;
    }

    // 新增用户
    public void addUser(UserManageView manageView, UserAttributeView attributeView) {
        String account = attributeView.getAccountCombo().getText();
        String name = attributeView.getNameCombo().getText();
        String college = attributeView.getCollegeCombo().getText();
        int index = attributeView.getSexModel().getSelectedIndex();
        Byte sex = (byte) index;
        String phone = attributeView.getPhoneCombo().getValueField().getText();
        boolean isAdmin = attributeView.getIsAdminBox().isSelected();
        User user = getUserByAccount(account);
        // 判断账号、姓名、学院是否为空
        Utils.checkFieldNull(attributeView.getAccountCombo().getValueField(), "账号不能为空！");
        Utils.checkFieldNull(attributeView.getNameCombo().getValueField(), "姓名不能为空！");
        Utils.checkFieldNull(attributeView.getCollegeCombo().getValueField(), "学院不能为空！");
        // 判断该账号用户是否已经存在
        if (user != null) {
            JOptionPane.showMessageDialog(null, "该账号已存在，请确认用户信息！", "警告", JOptionPane.WARNING_MESSAGE);
            return;
        } else {
            user = new User();
            user.setAccount(account);
            user.setName(name);
            user.setCollege(college);
            user.setSex(sex);
            user.setPhone(phone);
            user.setAdmin(isAdmin);
            user.setPassword("E10ADC3949BA59ABBE56E057F20F883E"); // 默认密码是123456
            user.setAvatarSrc("images/Avatar/default.png"); // 默认头像
            // System.out.println("user:" + user);
            boolean inserted = userDao.insertUser(user);// 添加用户
            if (!inserted) {
                // 如果添加失败
                JOptionPane.showMessageDialog(null, "新增用户失败", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            manageView.refreshTableData(); // 刷新数据
            attributeView.dispose();
            JOptionPane.showMessageDialog(null, "新增用户成功！");
        }
    }


    // 修改用户信息
    public void modifyUserInfo(UserManageView userManageView) {
        int rowId = userManageView.getTableDataView().getSelectedRow();
        if (rowId == -1) {
            JOptionPane.showMessageDialog(null, "请选择要修改的用户！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        // 获取账号
        String accountField = (String) userManageView.getTableDataView().getValueAt(rowId, 1);
        String account = accountField.replace(" ", "");
        // 打开用户属性页面
        new UserAttributeView(userManageView, "修改用户信息", account, false);
    }

    // 删除用户
    public void deleteUser(UserManageView userManageView) {
        User operator = userManageView.getMainView().getUser();
        // 获取选中的最上面一行数据
        int rowId = userManageView.getTableDataView().getSelectedRow();
        if (rowId == -1) {
            JOptionPane.showMessageDialog(null, "请选择要删除的用户！", "警告", JOptionPane.WARNING_MESSAGE);
            return;
        }
        // 获取账号
        String accountField = (String) userManageView.getTableDataView().getValueAt(rowId, 1);
        String account = accountField.replace(" ", "");
        if (operator.getAccount().equals(account)) {
            JOptionPane.showMessageDialog(null, "不能删除自己！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        int choose = JOptionPane.showConfirmDialog(null, "请确认是否删除" + account + "用户信息", "警告", JOptionPane.YES_NO_OPTION);
        if (choose == JOptionPane.YES_OPTION) {
            boolean deleted = userDao.deleteUserByAccount(account);
            userManageView.refreshTableData();
            if (!deleted) {
                //如果删除失败
                JOptionPane.showMessageDialog(null, "删除失败", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            JOptionPane.showMessageDialog(null, "已删除用户" + account);
        }
    }

    // 重置用户密码
    public void resetUserPwd(UserManageView userManageView) {
        // 获取选中的最上面一行数据
        int rowId = userManageView.getTableDataView().getSelectedRow();
        if (rowId == -1) {
            JOptionPane.showMessageDialog(null, "请选择要重置密码的用户！", "警告", JOptionPane.WARNING_MESSAGE);
            return;
        }
        // 获取账号
        String accountField = (String) userManageView.getTableDataView().getValueAt(rowId, 1);
        String account = accountField.replace(" ", "");
        User user = getUserByAccount(account);
        // 打开重置密码页面
        new ChangePwdView(userManageView, user, false);
    }

    // 查看用户信息
    public void viewUserInfo(UserManageView userManageView) {
        int rowId = userManageView.getTableDataView().getSelectedRow();
        if (rowId == -1) {
            JOptionPane.showMessageDialog(null, "数据获取错误！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        // 获取账号
        String accountField = (String) userManageView.getTableDataView().getValueAt(rowId, 1);
        String account = accountField.replace(" ", "");
        // 打开用户属性页面
        new UserAttributeView(userManageView, "查看用户信息", account, true);
    }

    // 获取查询的用户
    public void getSearchUser(UserManageView userManageView) {
        List<User> list = new ArrayList<>();
        // 获取输入的查询方式：0-账 号，1-姓 名，2-学 院，3-电 话
        JComboBox searchWay = userManageView.getSearchWay();
        int index = searchWay.getSelectedIndex();
        // 获取输入的查询信息
        JTextField searchInfo = userManageView.getSearchInfo();
        String sqlKey = "%" + searchInfo.getText() + "%";
        if (sqlKey == null || sqlKey.length() == 0) {
            list = userDao.selectUserBySql("select * from user order by account", null);
        } else {
            String sql = "select * from user where ";
            switch (index) {
                case 0:
                    System.out.println("搜索：账 号");
                    sql = sql + "account ";
                    break;
                case 1:
                    System.out.println("搜索：姓 名");
                    sql = sql + "name ";
                    break;
                case 2:
                    System.out.println("搜索：学 院");
                    sql = sql + "college ";
                    break;
                case 3:
                    System.out.println("搜索：电 话");
                    sql = sql + "phone ";
                    break;
                default:
                    System.out.println("default");
                    sql = sql + "account "; // 默认查询账号
                    break;
            }
            sql = sql + "like ? order by account";
            list = userDao.selectUserBySql(sql, sqlKey);
        }
        userManageView.setTableData(list);
    }

}
